/*
 * Copyright (C) 2015 Bilibili
 * Copyright (C) 2015 Zhang Rui <bbcallen@gmail.com>
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.living.player.services;

import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.living.Constant;
import com.living.R;
import com.living.player.db.AudioPlayListManger;
import com.living.player.event.EventMediaChange;
import com.living.player.event.EventPlayNewData;
import com.living.player.event.EventStatusPause;
import com.living.player.event.EventStatusPlay;
import com.living.player.ui.player.VideoActivity;
import com.md.basedpc.persistence.PHSPUtil;
import com.md.network.api.Audio;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.NotificationCompat;
import tv.danmaku.ijk.media.player.IMediaPlayer;

/**
 * 实现 自动联播、播放数据 暂存和播放监听的功能
 */
public class MediaPlayerServiceImp extends MediaPlayerService {

    public static final String TAG = "MediaPlayerServiceImp";
    static Application application;
    static Activity currentActivity;
    private static NotificationManager notificationManager;
    private static int notification_id_int = 3306;
    private String notificationId = "channelId";
    private String notificationName = "channelName";

    private static Audio currentPlayAudio;

    public static Audio getCurrentPlayAudio() {
        return currentPlayAudio;
    }

    public static void setCurrentPlayAudio(Audio currentPlayAudio) {
        MediaPlayerServiceImp.currentPlayAudio = currentPlayAudio;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        // 播放记录 的展示
        List<Audio> audioList = AudioPlayListManger.getInstance().getAllRecentAudios();
        Log.e(TAG, "onCreate: size == " + audioList.size());
        if (audioList.size() > 0 && currentPlayAudio == null) {
            String audioId = PHSPUtil.getInstance().getString(Constant.player_recent_audio_id, "");
            Log.e(TAG, "onCreate: audioId == " + audioId);
            // 顺序播放
            for (int i = 0; i < audioList.size() - 1; i++) {
                if (audioList.get(i).getId().equals(audioId)) {
                    currentPlayAudio = audioList.get(i);
                    Log.e(TAG, "onCreate: currentPlayAudio == " + currentPlayAudio.getId());
                    break;
                }
            }
        }
        application = getApplication();
        initButtonReceiver();
        application.registerActivityLifecycleCallbacks(new Application.ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                currentActivity = activity;
            }

            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }

            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {

            }
        });
    }

    @Override
    protected void onEventRev(Object event) {
        if (event instanceof EventPlayNewData) {
            currentPlayAudio = ((EventPlayNewData) event).getAudio();
        } else if (event instanceof EventStatusPlay) {
            // todo nothing
            updateNotification();
        } else if (event instanceof EventStatusPause) {
            // todo nothing
            updateNotification();
        }
    }

    public static void playAudio(Context context, Audio audio) {
        currentPlayAudio = audio;
        EventBus.getDefault().post(new EventPlayNewData(audio));
        PHSPUtil.getInstance().putString(Constant.player_recent_audio_id, audio.getId());
        ServicePlayUtils.playPath(context.getApplicationContext(), audio.getAudioUrl());
        EventBus.getDefault().post(new EventMediaChange());
        EventBus.getDefault().post(new EventStatusPlay());
    }

    /***
     * 下一首
     * @return
     */
    public static Audio getNextAudio() {
        Audio audio = null;
        List<Audio> audioList = AudioPlayListManger.getInstance().getAllRecentAudios();
        // 顺序播放
        for (int i = 0; i < audioList.size() - 1; i++) {
            if (audioList.get(i).getId().equals(currentPlayAudio.getId())) {
                audio = audioList.get(i + 1);
                break;
            }
        }
        return audio;
    }

    /***
     * 上一首
     * @return
     */
    public static Audio getLastAudio() {
        Audio audio = null;
        List<Audio> audioList = AudioPlayListManger.getInstance().getAllRecentAudios();
        // 顺序播放
        for (int i = 1; i < audioList.size(); i++) {
            if (audioList.get(i).getId().equals(currentPlayAudio.getId())) {
                audio = audioList.get(i - 1);
                break;
            }
        }
        return audio;
    }

    /**
     * 顺序播放 、 单曲循环 、 随机播放
     *
     * @param mp
     */
    protected static void onPlayComplete(IMediaPlayer mp) {
        List<Audio> audioList = AudioPlayListManger.getInstance().getAllRecentAudios();
        if (audioList.size() > 0 && currentPlayAudio != null) {
            int order = PHSPUtil.getInstance().getInt(Constant.player_order, 0);
            if (order == 0) {
                // 顺序播放
                for (int i = 0; i < audioList.size() - 1; i++) {
                    if (audioList.get(i).getId().equals(currentPlayAudio.getId())) {
                        currentPlayAudio = audioList.get(i + 1);
                        break;
                    }
                }
                playAudio(application, currentPlayAudio);
            } else if (order == 1) {
                // 单曲循环
                playAudio(application, currentPlayAudio);
            } else {
                // 随机播放
                int pos = (int) (Math.random() * audioList.size() - 1);
                currentPlayAudio = audioList.get(pos);
                playAudio(application, currentPlayAudio);
            }
        }
    }

    private static void playNext() {
        List<Audio> audioList = AudioPlayListManger.getInstance().getAllRecentAudios();
        // 顺序播放
        for (int i = 0; i < audioList.size() - 1; i++) {
            if (audioList.get(i).getId().equals(currentPlayAudio.getId())) {
                currentPlayAudio = audioList.get(i + 1);
                break;
            }
        }
        playAudio(application, currentPlayAudio);
    }

    private static void playLast() {
        List<Audio> audioList = AudioPlayListManger.getInstance().getAllRecentAudios();
        // 顺序播放
        for (int i = 0; i < audioList.size() - 1; i++) {
            if (audioList.get(i).getId().equals(currentPlayAudio.getId()) && (i - 1) > 0) {
                currentPlayAudio = audioList.get(i - 1);
                break;
            }
        }
        playAudio(application, currentPlayAudio);
    }


    /**
     * 播放失败
     *
     * @param mp
     */
    protected static void onPlayCompleteError(IMediaPlayer mp) {

    }

    private static void updateNotification() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager) application.getSystemService(Context.NOTIFICATION_SERVICE);
        }
        String title = currentPlayAudio.getName();
        String content = currentPlayAudio.getAuthor() + " 《" + currentPlayAudio.getAlbumName() + "》";
//        Intent clickIntent = new Intent(currentActivity, VideoActivity.class);
        // 得到PendingIntent
//        PendingIntent pendIntent_click = PendingIntent.getBroadcast(currentActivity, 1121, clickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        PendingIntent pendIntent_click = toMainActivity(currentActivity);
        String channel_id = "yxt_lecai_app_channel_01";
        String name = application.getApplicationContext().getResources().getString(R.string.app_name);
        Notification notification = null;
        Notification.Builder notificationBuilder = null;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel mChannel = new NotificationChannel(channel_id, name, NotificationManager.IMPORTANCE_DEFAULT);
            notificationManager.createNotificationChannel(mChannel);
            notificationBuilder = new Notification.Builder(application, channel_id);
        } else {
            notificationBuilder = new Notification.Builder(application);
        }
        // 大个的自定义通知栏（高度最大 256dp）
        RemoteViews mRemoteViews = new RemoteViews(application.getPackageName(), R.layout.layout_notification_player_item);
        mRemoteViews.setTextViewText(R.id.tv_notify_title, title + "");
        mRemoteViews.setTextViewText(R.id.tv_notify_content, content + "");
        if (sMediaPlayer != null && sMediaPlayer.isPlaying()) {
            mRemoteViews.setImageViewResource(R.id.iv_notify_status, R.drawable.icon_player_notify_pause);
        } else {
            mRemoteViews.setImageViewResource(R.id.iv_notify_status, R.drawable.icon_player_notify_playing);
        }
        Intent buttonIntent = new Intent(ACTION_BUTTON);
        /* 上一首按钮 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PREV_ID);
        //这里加了广播，所及INTENT的必须用getBroadcast方法
        PendingIntent intent_prev = PendingIntent.getBroadcast(application, 1, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.iv_notify_last, intent_prev);
        /* 播放/暂停  按钮 */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_PALY_ID);
        PendingIntent intent_paly = PendingIntent.getBroadcast(application, 2, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.iv_notify_status, intent_paly);
        /* 下一首 按钮  */
        buttonIntent.putExtra(INTENT_BUTTONID_TAG, BUTTON_NEXT_ID);
        PendingIntent intent_next = PendingIntent.getBroadcast(application, 3, buttonIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        mRemoteViews.setOnClickPendingIntent(R.id.iv_notify_next, intent_next);

        notificationBuilder
                .setContent(mRemoteViews)
                .setContentTitle(application.getResources().getString(R.string.app_name))
                .setContentText(application.getResources().getString(R.string.app_name))
                .setContentIntent(pendIntent_click)
                .setSmallIcon(R.drawable.icon_download_disable)
                .setOngoing(true); //无效
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            notificationBuilder.setCustomBigContentView(mRemoteViews);
        }
        notification = notificationBuilder.build();
        notification.contentIntent = pendIntent_click;
        notification.contentView = mRemoteViews;

        notificationManager.notify(notification_id_int, notification);
    }


    private static PendingIntent toMainActivity(Activity activity) {
        //点击广播监听
        Intent intentClick = new Intent(activity, VideoActivity.class);
        //如果跳转的activity 是一个普通的设置FLAG_ACTIVITY_NEW_TASK即可，
        //如果是一个singletask activity 则需要添加FLAG_ACTIVITY_CLEAR_TOP ，否则启动可能失败
        intentClick.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intentClick.addCategory("android.intent.category.DEFAULT");
        intentClick.setAction("android.intent.action.SEND");
        return PendingIntent.getActivity(activity, 0, intentClick, 0);
    }


    public void initButtonReceiver() {
        bReceiver = new ButtonBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_BUTTON);
        registerReceiver(bReceiver, intentFilter);

    }

    public final static String INTENT_BUTTONID_TAG = "ButtonId";
    /**
     * 上一首 按钮点击 ID
     */
    public final static int BUTTON_PREV_ID = 1;
    /**
     * 播放/暂停 按钮点击 ID
     */
    public final static int BUTTON_PALY_ID = 2;
    /**
     * 下一首 按钮点击 ID
     */
    public final static int BUTTON_NEXT_ID = 3;
    public ButtonBroadcastReceiver bReceiver;
    public final static String ACTION_BUTTON = "com.weidongjian.weigan.ButtonClick";

    public class ButtonBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, " ButtonBroadcastReceiver");
            // TODO Auto-generated method stub
            String action = intent.getAction();
            if (action.equals(ACTION_BUTTON)) {
                //通过传递过来的ID判断按钮点击属性或者通过getResultCode()获得相应点击事件
                int buttonId = intent.getIntExtra(INTENT_BUTTONID_TAG, 0);
                switch (buttonId) {
                    case BUTTON_PREV_ID:
                        Log.d(TAG, "上一首01");
                        playLast();
                        break;
                    case BUTTON_PALY_ID:
                        Log.d(TAG, "play");
                        if (isPlayable()) {
                            if (isPlaying()) {
                                pausePlay();
                            } else {
                                startPlay();
                            }
                            updateNotification();
                        }
                        break;
                    case BUTTON_NEXT_ID:
                        Log.d(TAG, "next song");
                        playNext();
                        break;
                    default:
                        break;
                }
            }
        }
    }


}
